<!DOCTYPE html>
<html lang="zh-CN">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>表格</title>
    <style>
      table,
      th,
      td {
        border: 1px solid rgb(5, 5, 5);
      }
      table {
        border-collapse: collapse;
      }
    </style>
  </head>
  <body>
    <table id="userTable">
      <tr>
        <th>姓名</th>
        <th>年龄</th>
        <th>地址</th>
        <th>操作</th>
      </tr>
      <!-- <tr>
        <td>张三</td>
        <td>23</td>
        <td>学院路1号</td>
      </tr>
      <tr>
        <td>李四</td>
        <td>24</td>
        <td>学院路2号</td>
      </tr> -->
    </table>
    <script>
      const data = [
        { name: "张三", age: "23", address: "学院路1号" },
        { name: "李四", age: "24", address: "学院路2号" },
      ];
      const userTable = document.getElementById("userTable");
      data.forEach((user, index) => {
        const tr = document.createElement("tr");
        tr.dataset.index = index;
        const values = Object.values(user);
        for (let it of values) {
          const td = document.createElement("td");
          td.textContent = it;
          tr.append(td);
        }
        userTable.append(tr);
        const td = document.createElement("td");
        const button_et = document.createElement("button");
        button_et.textContent = "编辑";
        button_et.classList.add("btn-edit");
        td.append(button_et);
        const button_dl = document.createElement("button");
        button_dl.textContent = "删除";
        button_dl.classList.add("btn-delete");
        td.append(button_dl);
        tr.append(td);
      });
      userTable.addEventListener("click", (event) => {
        const btnDelete = event.target.closest("button.btn-delete");
        if (!btnDelete || !userTable.contains(btnDelete)) return;
        const tr = btnDelete.closest("tr");
        if (tr) tr.remove();
      });
      userTable.addEventListener("click", (event) => {
        const btnEdit = event.target.closest("button.btn-edit");
        if (!btnEdit || !userTable.contains(btnEdit)) return;
        const tr = btnEdit.closest("tr");
        if (tr) {
          const index = tr.dataset.index;
          console.log(data[index]);
        }
      });
    </script>
  </body>
</html>
